import { Injectable } from '@nestjs/common';
import { ValidatorConstraint, ValidatorConstraintInterface, ValidatorOptions, registerDecorator } from 'class-validator'
import { QueryBus } from '@nestjs/cqrs';
import { UserExistQuery } from '../queris/user-exist.query';


@Injectable()
@ValidatorConstraint({ async: true })
export class UserNotExistValidator implements ValidatorConstraintInterface {
  constructor(
    private readonly queryBus: QueryBus,
  ) { }
  async validate(value: string) {
    const result = await this.queryBus.execute(new UserExistQuery({ username: value }))
    return !result
  }
  defaultMessage() {
    return '用户已存在'
  }
}

/**
 * 验证用户是否存在装饰器
 * @param {ValidatorOptions} options ValidatorOptions
 * @returns 
 */
export const IsUserNotExits = (options?: ValidatorOptions) => {
  return function (object: Object, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: options,
      constraints: [],
      validator: UserNotExistValidator,
    });
  };
}